package common.coucurrency.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created by Gerardo on 1/27/14.
 */
public class RailwayStation {
	private static Lock station = new ReentrantLock();
	private static Condition joeArrival = station.newCondition();

	static class Train extends Thread {
		Train(final String name) {
			super(name);
		}

		@Override
		public void run() {
			station.lock();
			try {
				System.out.println(getName() + ": arrived in station");
				if (getName().startsWith("IC1122")) {
					joeArrival.signalAll();
				}
			} finally {
				station.unlock();
			}
		}
	}

	static class WaitForJoe extends Thread {
		@Override
		public void run() {
			System.out.println("Waiting in station IC1122");
			station.lock();
			try {
				System.out.println("wait");
				joeArrival.await();
				System.out.println("Hello Joe");
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				station.unlock();
			}
		}
	}
}
